<?php

class people extends CI_Controller {
		
	function __construct() {
		parent::__construct();
		$this->load->helper('form');
		$this->load->library('form_validation');
		if( $this->session->userdata('logged_in')){
			$this->load->model('people_model');
			$this->load->model('SluzobneCesty_model');
			$this->load->model('logs_model');
			//$this->load->view('hlavna_stranka_view');
		} else {
			//$this->load->view('neprihlaseny_view');
            redirect(site_url('SluzobneCesty'));	
		}
	}
	
	function index(){
		  
			$this->load->library('pagination');
			$config = array(
				'base_url' => base_url().'people/index',
				'total_rows' => $this->db->count_all_results('people'),
				'per_page' => 20,
				'first_link' => 'Prvý',
				'last_link' => 'Posledný',
				'full_tag_open' => '<div id="strankovanie">',
				'full_tag_close' => '</div>'				
			);
			
			$this->pagination->initialize($config);
			$data['people'] = $this->people_model->GetAll($config['per_page'],$this->uri->segment(3));
			$this->load->view('people_view',$data);
		
	}
	
	function search(){
		$response = array();
		if( mb_strlen(trim($this->input->post('str')),'utf-8') > 0 ){
			$to_search = explode(' ',trim($this->input->post('str')));
			$table = $this->input->post('typ_cesty');
			$q = 'SELECT * FROM people WHERE';
			if( sizeof($to_search) > 0 ){
				foreach ($to_search as $key => $value) {
					$q .= ' name LIKE ' . "'%".$this->db->escape_like_str($value)."%'" . ' OR surname LIKE '."'%".$this->db->escape_like_str($value)."%'" . 'OR';
				}
				$q = substr($q, 0, -2);
				$q .= ' LIMIT 20';
			}
			
			$result = $this->db->query($q);
			foreach ($result->result_array() as $key => $personArr) {
				$response[$personArr['person_id']] = $personArr['surname'] . ' ' . $personArr['name'] . ' / ' . $personArr['department'];	
			}
		}
		echo json_encode($response);			
	}
	
	function _getPeople($ids){
		$pole_ids = explode(',', $ids);
		$result = array();
		for ($i=0; $i < sizeof($pole_ids); $i++) { 
			$result[$i] = $this->people_model->GetPerson($pole_ids[$i]);		
		}
		return $result;
	}
	
	function ukaz($id){
		$pageData['cesty'] = $this->people_model->getCestyWherePID($id);
		$pageData['clovek'] = $this->people_model->GetPerson($id);
		$this->load->view('clovek_podrobnosti_view', $pageData);
	}
	
	function uniqueEmail($email){
		$result = $this->people_model->checkUnikatnyEmail($email);
		if( $result ){
			//email neexistuje
			return TRUE;	
		} else {
			$this->form_validation->set_message('uniqueEmail', 'Emailová adresa musí byť unikátna.');
			return FALSE;	
		}
	}
	
	function pridatCloveka(){

		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		//nastavenie validacie
		$this->form_validation->set_rules('name','<b><u>Meno</u></b>','required|trim|addslashes');
		$this->form_validation->set_rules('surname','<b><u>Priezvisko</u></b>','required|trim|addslashes');
		
		$this->form_validation->set_rules('degree','<b><u>Titul</u></b>','trim|addslashes');
		$this->form_validation->set_rules('degree2','<b><u>Titul</u></b>','trim|addslashes');
		$this->form_validation->set_rules('degree3','<b><u>Titul</u></b>','trim|addslashes');
		
		$this->form_validation->set_rules('sex[]','<b><u>Pohlavie</u></b>','');
		$this->form_validation->set_rules('sektion','<b><u>Sekcia</u></b>','trim|addslashes');
		$this->form_validation->set_rules('department','<b><u>Oddelenie</u></b>','required|trim|addslashes');
		$this->form_validation->set_rules('chair','<b><u>Kancelária</u></b>','trim|addslashes');
		$this->form_validation->set_rules('email','<b><u>Emailová adresa</u></b>','required|valid_email|callback_uniqueEmail');
		$this->form_validation->set_rules('tel','<b><u>Telefónne číslo</u></b>','trim|addslashes');	
		$this->form_validation->set_rules('web_address','<b><u>Web adresa</u></b>','trim|addslashes');
		$this->form_validation->set_rules('is_deployed[]','<b><u>Je zamestnaný</u></b>','');
		$this->form_validation->set_rules('date_of_birth','<b><u>Dátum narodenie</u></b>','trim|addslashes');
		//$this->form_validation->set_rules('trip_type','Trip type','required|trim|addslashes');
	  
		$table = $this->input->post('typ_cesty');
		$cesta_id = $this->input->post('cesta_id');	
		//vytvorim pole $pageData aby som mohol este raz vygenerovat stranku cesta_podrobnosti_view		
		$pageData['cesta'] = $this->SluzobneCesty_model->getCestuById($table, $cesta_id); 	
		$pageData['typ_cesty'] = $this->input->post('typ_cesty');
		$pageData['id_cesty'] = $cesta_id;
		
		
		if( !empty($pageData['cesta'][0]['person_id']) ){
			$pageData['priradeni_ludia'] = $this->_getPeople($pageData['cesta'][0]['person_id']); 
			$tmp_ids = explode(',', $pageData['cesta'][0]['person_id']);//pole ids ludi ktore su priradeni k ceste, tychto ludi uz nedam do dropboxu
		}
	
		$ludia = $this->people_model->getAll();//vyberiem vsetkych ludi
		if( isset($tmp_ids) ){//ak je niekto priradeny k ceste  					
			//vytvorim asoc pole pre form drop_down 
			foreach ($ludia as $key => $obj) {
				$meno = $obj['name'] . ' ' . $obj['surname'];
				if( !in_array($obj['person_id'], $tmp_ids) ){ //ak clovek este nie je priradeny k ceste tak ho dame do dropboxu
					$options_drop_box[$obj['person_id']] = $meno;
				}
			}
		} else {//ak este nikto nie je priradeny tak do dropboxu dam vsetkych
			foreach ($ludia as $key => $obj) {
				$meno = $obj['name'] . ' ' . $obj['surname'];
					$options_drop_box[$obj['person_id']] = $meno;
				}
		}
	
		if( isset($options_drop_box) ){	
			$pageData['options_drop_box'] = $options_drop_box;//nastavenie form dropdown
		}
		$pageData['id_cesty'] = $cesta_id;					
		if( $this->form_validation->run() == FALSE ){//zle vyplneny formular
			$this->load->view('cesta_podrobnosti_view',$pageData); //loadujeme prislusny view
		} else {
			//dobre vyplneny form spracuvame data
				//data o clovekovi koho zapiseme do DB
				$tmp_sex = $this->input->post('sex');
				$tmp_is_deployed = $this->input->post('is_deployed');
				if( isset($tmp_is_deployed) && $tmp_is_deployed ){
               $tmp_is_deployed = $this->input->post('is_deployed');
            } else {
               $tmp_is_deployed = 1;
            }
         if( !isset($_POST['sex'][0]) ) $sex = NULL; else $sex = $_POST['sex'][0];
         if( !isset($_POST['is_deployed'][0]) ) $is_deployed = 1; else $is_deployed = $_POST['is_deployed'][0];	
            
            
				$personData = array(
					'person_id' => NULL,
					'degree' => $this->input->post('degree'),
					'degree2' => $this->input->post('degree2'),
					'name' => $this->input->post('name'),
					'surname' => $this->input->post('surname'),
					'degree3' => $this->input->post('degree3'),
					'sex' => $sex,
					'sektion' => $this->input->post('sektion'),
					'department' => $this->input->post('department'),
					'chair' => $this->input->post('chair'),
					'email' => $this->input->post('email'),
					'tel' => $this->input->post('tel'),
					'web_address' => $this->input->post('web_address'),
					'is_deployed' => $is_deployed,
					'date_of_birth' => $this->input->post('date_of_birth'),
					//'trip_type' => $this->input->post('trip_type')	
				);
				
				
				$obj_id_cloveka = $this->people_model->AddPerson($personData);
				$id_cloveka = $obj_id_cloveka['person_id']; //id cloveka koho naposledy pridali do db
				$pageData['id_cesty'] = $cesta_id;
				if( $id_cloveka != FALSE ){
					
					$obj_cesta = $this->SluzobneCesty_model->getCestuById($table, $cesta_id); //vyberiem cestu ku ktoremu chcem priradit cloveka
					$pids = $obj_cesta[0]['person_id']; //vyberiem policko person_id
					if( empty($pids) ){
						//este nebol nikto priradeny
						$pids = $id_cloveka;
						$obj_cesta[0]['person_id'] = $pids;
						$priradene = $this->SluzobneCesty_model->zmen($table, $obj_cesta[0]);
					} else {
						$tmp_pids = explode(',', $pids);
						$i = 0;
						while (($i < sizeof($tmp_pids)) && ($tmp_pids[$i] != $id_cloveka)) {
							$i++;
						}	
						if( $i < sizeof($tmp_pids) ){//clovek uz je priradeny k ceste 
							$pageData['clovek_existujuci'] = TRUE;
							$this->load->view('cesta_podrobnosti_view', $pageData);	
							//return;						
						} else {//este nie je priradeny
							$pids .= ','.$id_cloveka;
							$obj_cesta[0]['person_id'] = $pids;
							$priradene = $this->SluzobneCesty_model->zmen($table, $obj_cesta[0]);		
						}
					}
					
					
					///////////////////////////////////////////////////////////////////////////////////////////////
					//vytvorim pole $pageData aby som mohol este raz vygenerovat stranku cesta_podrobnosti_view
					//uz to raz hore mam vytvorene ale urobim to aj tu aby stranka normalne refreshla
					//ak formular bol dobre vyplneny tak aby uz aj novozapisane data sa ukazali na stranke		
					$pageData['cesta'] = $this->SluzobneCesty_model->getCestuById($table, $cesta_id); 	
					$pageData['typ_cesty'] = $this->input->post('typ_cesty');
					$pageData['id_cesty'] = $cesta_id;
					if( !empty($pageData['cesta'][0]['person_id']) ){
						$pageData['priradeni_ludia'] = $this->_getPeople($pageData['cesta'][0]['person_id']);//pridam ludi ktori su priradeni k ceste 
						$tmp_ids = explode(',', $pageData['cesta'][0]['person_id']);//pole ids ludi ktore su priradeni k ceste, tychto ludi uz nedam do dropboxu
					}
					
					$ludia = $this->people_model->getAll();//vyberiem vsetkych ludi 					
					//vytvorim asoc pole pre form drop_down 
					foreach ($ludia as $key => $obj) {
						$meno = $obj['name'] . ' ' . $obj['surname'];
						if( !in_array($obj['person_id'], $tmp_ids) ){ //ak clovek este nie je priradeny k ceste tak ho dame do dropboxu
							$options_drop_box[$obj['person_id']] = $meno;
						}
					}
					if( isset($options_drop_box) ){	
						$pageData['options_drop_box'] = $options_drop_box;//nastavenie form dropdown
					}
					///////////////////////////////////////////////////////////////////////////////////////////////
					
					if( $priradene ) {
					 
						$pageData['clovek_pridany'] = TRUE;
						$logsAction = 'pridal:' . $id_cloveka . ':' . $personData['name'] . ':' . $personData['surname']; //vytvorim action co urobil user
						$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
						$this->load->view('cesta_podrobnosti_view', $pageData);
					}
				} else {
				
					//cloveka nepodarilo zapisat do db
					//loadujeme cesta_podrobnosti_view este raz
					$this->load->view('cesta_podrobnosti_view', $pageData);
					
				}
				
			//}			
		}	
		
		
	}	 
	
	//priradi uz existujuceho cloveka v db k ceste
	function addExisting($table = '', $cesta_id = '', $person_id = ''){
		$pageData = array();
		$pageData['id_cesty'] = $cesta_id;
		$priradene = FALSE; //ci clovek bol alebo nebol priradiny k ceste
		if( empty($table) && empty($cesta_id) && empty($person_id)){
			$person_id = $this->input->post('ludia');//id cloveka koho chceme priradit k ceste
			$table = $this->input->post('typ_cesty');//tabulka do ktorej chceme zapisat
			$cesta_id = $this->input->post('cesta_id');//id cesty
		}
		
		$cestaArr = $this->SluzobneCesty_model->getCestuById($table, $cesta_id);//cesta ku ktoremu priradime cloveka
		
		$uzJePriradeni = FALSE;
		$priradeniLudia = explode(',', $cestaArr[0]['person_id']);
		foreach ($priradeniLudia as $key => $value) {
			if( $person_id == $value ){
				$uzJePriradeni = TRUE;
			}
		}
		
		if( empty($cestaArr[0]['person_id']) ){
			//este nikto nie je priradeny
			$ids = $person_id;
		} else {
			$ids = $cestaArr[0]['person_id'] . ',' . $person_id;
		}
		
		if( !$uzJePriradeni ){
			$priradene = $this->SluzobneCesty_model->zmenPids($table, $cesta_id, $ids);
		}		
		//vytvorim pole $pageData aby som mohol este raz vygenerovat stranku cesta_podrobnosti_view		
		$pageData['cesta'] = $this->SluzobneCesty_model->getCestuById($table, $cesta_id); 	
		$pageData['typ_cesty'] = $table;//do ktorej tabulky priradujeme ludi
		$pageData['id_cesty'] = $cesta_id;

		if( !empty($pageData['cesta'][0]['person_id']) ){
			$pageData['priradeni_ludia'] = $this->_getPeople($pageData['cesta'][0]['person_id']);
			$tmp_ids = explode(',', $pageData['cesta'][0]['person_id']);//pole ids ludi ktore su priradeni k ceste, tychto ludi uz nedam do dropboxu 
		}
		
		$ludia = $this->people_model->getAll();//vyberiem vsetkych ludi 					
		//vytvorim asoc pole pre form drop_down 
		foreach ($ludia as $key => $obj) {
			$meno = $obj['name'] . ' ' . $obj['surname'];
			if( !empty($tmp_ids) ){
				if( !in_array($obj['person_id'], $tmp_ids) ){ //ak clovek este nie je priradeny k ceste tak ho dame do dropboxu
					$options_drop_box[$obj['person_id']] = $meno;
				}
			} else {
				$options_drop_box[$obj['person_id']] = $meno;
			}
		}

		$pageData['options_drop_box'] = $options_drop_box;//nastavenie form dropdown

		
		if( $priradene ) {
			$pageData['clovek_pridany'] = TRUE;
			$tmp_clovek = $this->people_model->GetPerson($person_id);
			$logsAction = 'pridal existujuceho:' . $person_id . ':' . $tmp_clovek->name . ':' . $tmp_clovek->surname; //vytvorim action co urobil user
			$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
			$this->load->view('cesta_podrobnosti_view', $pageData);
		} else {
			$pageData['clovek_pridany'] = FALSE;
			$tmp_clovek = $this->people_model->GetPerson($person_id);
			$this->load->view('cesta_podrobnosti_view', $pageData);			
		}				
	}

	
	
	
	//vyberie jedneho cloveka podla ID
	function GetPerson($id){
		return $this->people_model->GetPerson($id);			
	}
	
	function GetPersonEdit($id){
		$data = $this->people_model->GetPerson($id);
		$this->load->view('people_view',$data);	
	}
	

	
	//edit cloveka
	function Edit(){
		
		//nastavenie validacie
		$this->form_validation->set_rules('name','Name','required|trim|addslashes');
		$this->form_validation->set_rules('surname','Surname','required|trim|addslashes');
		$this->form_validation->set_rules('degree','Degree','required|trim|addslashes');
		$this->form_validation->set_rules('sex','Sex','required|trim|addslashes');
		$this->form_validation->set_rules('sektion','Sektion','required|trim|addslashes');
		$this->form_validation->set_rules('department','Department','required|trim|addslashes');
		$this->form_validation->set_rules('chair','Chair','required|trim|addslashes');
		$this->form_validation->set_rules('email','Email','required|valid_email');
		$this->form_validation->set_rules('tel','Tel','required|trim|addslashes');	
		$this->form_validation->set_rules('web_address','Web','required|trim|addslashes');
		$this->form_validation->set_rules('is_deployed','Deployed','required|trim|addslashes');
		$this->form_validation->set_rules('date_of_birth','Date of birth','required|trim|addslashes');
		$this->form_validation->set_rules('trip_type','Trip type','required|trim|addslashes');
		
		if( $this->form_validation->run() == FALSE ){
			//zle vyplneny formular
			$this->load->view('people_view'); //loadujeme prislusny view
		} else { //dobre vyplneny form spracuvame data
			if( !isset($_POST['sex'][0]) ) $_POST['sex'][0] = NULL;
         if( !isset($_POST['is_deployed'][0]) ) $_POST['is_deployed'][0] = 1;	
         
         
         if( !isset($_POST['sex'][0]) ) $sex = NULL; else $sex = $_POST['sex'][0];
         if( !isset($_POST['is_deployed'][0]) ) $is_deployed = 1; else $is_deployed = $_POST['is_deployed'][0];	
			//data o clovekovi koho zapiseme do DB
			$personData = array(
				'person_id' => $this->input->post('person_id'),
				'name' => $this->input->post('name'),
				'surname' => $this->input->post('surname'),
				'degree' => $this->input->post('degree'),
				'sex' => $sex,
				'sektion' => $this->input->post('sektion'),
				'department' => $this->input->post('department'),
				'chair' => $this->input->post('chair'),
				'email' => $this->input->post('email'),
				'tel' => $this->input->post('tel'),
				'web_address' => $this->input->post('web_address'),
				'is_deployed' => $is_deployed,
				'date_of_birth' => $this->input->post('date_of_birth'),
				'trip_type' => $this->input->post('trip_type')	
			);
			
			$zmenene = $this->people_model->EditPerson($personData);
			if($zmenene){
				//zapisal sa do DB
				$logsAction = 'zmenil:' . $personData['person_id'] . ':' . $personData['name'] . ':' . $personData['surname']; //vytvorim action co urobil user
				$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
				$this->load->view('people_view');
			} else {
				//chyba pri zapise do DB
				//TODO
			}
		}
	}
	
	//delete
	function Delete($id){
		$tmp_clovek = $this->people_model->GetPerson($id);//vyberiem toho cloveka koho chceme zrusit

		$result = $this->people_model->DeletePerson($id);
		if($result){
			$logsAction = 'zrusil:' . $id . ':' . $tmp_clovek->name . ':' . $tmp_clovek->surname; //vytvorim action co urobil user
			$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
			return $result;
		} else {
			return FALSE;
		}
	}
	
	function All(){
		$data = $this->people_model->GetAll();
		return $data;
	}
	
	function upgrade_person(){
       
		//nastavenie validacie
		$this->form_validation->set_rules('name','Name','required|trim|addslashes');
		$this->form_validation->set_rules('surname','Surname','required|trim|addslashes');
		$this->form_validation->set_rules('degree_bef1','Degree','trim|addslashes');
		$this->form_validation->set_rules('degree_bef2','Degree','trim|addslashes');
		$this->form_validation->set_rules('degree_after','Degree','trim|addslashes');
		//$this->form_validation->set_rules('sex','Sex');
		$this->form_validation->set_rules('sektion','Sektion','trim|addslashes');
		$this->form_validation->set_rules('department','Department','required|trim|addslashes');
		$this->form_validation->set_rules('chair','Chair','trim|addslashes');
		$this->form_validation->set_rules('email','Email','required|valid_email');
		$this->form_validation->set_rules('tel','Tel','trim|addslashes');	
		$this->form_validation->set_rules('web_address','Web','trim|addslashes');
		//$this->form_validation->set_rules('is_deployed','Deployed','addslashes');
		$this->form_validation->set_rules('date_of_birth','Date of birth','trim|addslashes');
		
		if( $this->form_validation->run() == FALSE ){
			//zle vyplneny formular
			$page_data['person'] = $this->people_model->GetPerson($_POST['person_id']);	
			$this->load->view('people_podrobnosti_view', $page_data); //loadujeme prislusny view
		} else { //dobre vyplneny form spracuvame data
         if( !isset($_POST['sex'][0]) ) $sex = NULL; else $sex = $_POST['sex'][0];
         if( !isset($_POST['is_deployed'][0]) ) $is_deployed = 1; else $is_deployed = $_POST['is_deployed'][0];		
			//data o clovekovi koho zapiseme do DB
			$personData = array(
				'person_id' => $this->input->post('person_id'),
				'name' => $this->input->post('name'),
				'surname' => $this->input->post('surname'),
				'degree' => $this->input->post('degree'),
				'degree2' => $this->input->post('degree2'),
				'degree3' => $this->input->post('degree3'),
				'sex' => $sex,
				'sektion' => $this->input->post('sektion'),
				'department' => $this->input->post('department'),
				'chair' => $this->input->post('chair'),
				'email' => $this->input->post('email'),
				'tel' => $this->input->post('tel'),
				'web_address' => $this->input->post('web_address'),
				'is_deployed' => $is_deployed,
				'date_of_birth' => $this->input->post('date_of_birth')	
			);
			
			$zmenene = $this->people_model->EditPerson($personData);
			if($zmenene){
				//zapisal sa do DB
				$logsAction = 'zmenil:' . $personData['person_id'] . ':' . $personData['name'] . ':' . $personData['surname']; //vytvorim action co urobil user
				$this->logs_model->addLog($this->session->userdata('user_id'), $logsAction); //pridam do logs data a userId
				$page_data['zmenene'] = $zmenene;
				$this->load->view('people_podrobnosti_view', $page_data);
			} else {
				//chyba pri zapise do DB
				echo "chyba pri uograde cloveka";
				//TODO
			}
		}
			   
	   
	}
   
	function upgrade($id){  	
   		$page_data['person'] = $this->people_model->GetPerson($id);			
		$this->load->view('people_podrobnosti_view', $page_data);
    }			 
		 
    function getDegree() {
        $this->load->helper('autocomplete');
        $filter = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
        $data = simple_people_autocomplete('degree', $filter);
        echo json_encode($data);
    }
    
    function getDegree2() {
        $this->load->helper('autocomplete');
        $filter = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
        $data = simple_people_autocomplete('degree2', $filter);
        echo json_encode($data);
    }
    
    function getDegree3() {
        $this->load->helper('autocomplete');
        $filter = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
        $data = simple_people_autocomplete('degree3', $filter);
        echo json_encode($data);
    }
    
    function getDepartment() {
        $this->load->helper('autocomplete');
        $filter = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
        $data = simple_people_autocomplete('department', $filter);
        echo json_encode($data);
    }
    
    function getSektion() {
        $this->load->helper('autocomplete');
        $filter = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
        $data = simple_people_autocomplete('sektion', $filter);
        echo json_encode($data);
    }
    
    function getChair() {
        $this->load->helper('autocomplete');
        $filter = isset($_REQUEST['term']) ? $_REQUEST['term'] : ''; 
        $data = simple_people_autocomplete('chair', $filter);
        echo json_encode($data);
    }

}

?>
	